/* debug_serial.c -- AT91SAM7 serial output via DBGU
**
** Copyright 2006, Brian Swetland.  All rights reserved.
** See provided LICENSE file or http://frotz.net/LICENSE for details.
*/

#include "at91sam7s.h"
#include "devices.h"
#include "board.h"

//#ifndef MCK_IN_MHZ
//#error serial_debug module requires MCK_IN_MHZ
//#endif

void ser_init(void)
{
    AT91PIO *pio = AT91PIO_ADDR;
    AT91DBGU *dbgu = AT91DBGU_ADDR;

    pio->select_a = PIN_DRXD | PIN_DTXD;
    pio->pio_disable = PIN_DRXD | PIN_DTXD;
    
    dbgu->MR = DBGU_PAR_NONE | DBGU_MODE_NORMAL;
    dbgu->BRGR = 10; //MCK_IN_MHZ / 115200 / 16; 
    dbgu->CR = DBGU_RXEN | DBGU_TXEN;
}

void ser_putc(unsigned c)
{
    AT91DBGU *dbgu = AT91DBGU_ADDR;
    if(c == 10) {
        while(!(dbgu->SR & DBGU_TXRDY));
        dbgu->THR = 13;
    }
    while(!(dbgu->SR & DBGU_TXRDY));
    dbgu->THR = c;
}

void ser_puts(char *s)
{
    AT91DBGU *dbgu = AT91DBGU_ADDR;
    while(*s) {
        if(*s == 10) {
            while(!(dbgu->SR & DBGU_TXRDY));
            dbgu->THR = 13;
        }
        while(!(dbgu->SR & DBGU_TXRDY));
        dbgu->THR = *s++;
    }
}

